package han.cirno.corrupt.modules.report

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import androidx.activity.compose.LocalActivity
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import han.cirno.corrupt.R
import han.cirno.corrupt.activity.main.MainActivityViewModel
import han.cirno.corrupt.components.crash.CrashTypes
import han.cirno.corrupt.components.crash.CrashUtils.sendCrashReport
import han.cirno.corrupt.compose.localeStringResource
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

@Composable
fun ReportLayout(){
    val errorBrush = Brush.linearGradient(
        colors = listOf(MaterialTheme.colorScheme.error, MaterialTheme.colorScheme.error),
    )
    val mainActivityViewModel:MainActivityViewModel= hiltViewModel(LocalActivity.current as AppCompatActivity)
    val reports by mainActivityViewModel.reportsFlow.collectAsState(mutableListOf())
    LazyColumn(
        modifier = Modifier.fillMaxSize(),
        state = rememberLazyListState()) {
        items(reports){ ReportCard(it) }
        item{
            Box(
                modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
                contentAlignment = Alignment.Center) {
                OutlinedButton(
                    colors = ButtonDefaults.outlinedButtonColors(
                        contentColor = MaterialTheme.colorScheme.error),
                    border = CardDefaults.outlinedCardBorder().copy(brush = errorBrush),
                    onClick = {throw IllegalStateException("Manual exception")}) {
                    Text(
                        modifier = Modifier.padding(8.dp),
                        text= localeStringResource(R.string.report_crash),
                        color = MaterialTheme.colorScheme.error)
                }
            }
        }
    }
}

@Composable
fun ReportCard(triple: Triple<String,String,String>){
    val context= LocalContext.current
    val clipBoardManager = remember {
        context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    }
    val errorBrush = Brush.linearGradient(
        colors = listOf(MaterialTheme.colorScheme.error, MaterialTheme.colorScheme.error),
    )
    val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US) }
    val typeString= localeStringResource(when(triple.first){
        CrashTypes.CRASH-> R.string.report_type_crash
        CrashTypes.TASK_FAILED->R.string.report_type_refresh
        else->R.string.report_type_unknown
    })
    val timeString=run{dateFormat.format(Date((triple.second.substring(
        0,System.currentTimeMillis().toString().length)).toLongOrNull()
        ?:return@run localeStringResource(R.string.report_time_unknown))) }
    var copyClicked by remember { mutableStateOf(false) }
    val content:@Composable ColumnScope.()->Unit={
        Row(modifier = Modifier.fillMaxWidth().padding(8.dp), verticalAlignment = Alignment.CenterVertically) {
            Text(text="$typeString - $timeString", modifier = Modifier.weight(1f))
            Row(horizontalArrangement = Arrangement.End) {
                TextButton(onClick = {
                    copyClicked=true
                    clipBoardManager.setPrimaryClip(ClipData.newPlainText("Corrupt",
                        File(triple.third).readBytes().decodeToString()))
                }) { Text(text = localeStringResource(
                    if(copyClicked) R.string.report_copied else R.string.report_copy)) }
                TextButton(onClick = {
                    context.sendCrashReport(triple.third)
                }) { Text(text = localeStringResource(R.string.report_share)) }
            }
        }
    }
    val modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp, horizontal = 16.dp)
    if (triple.first==CrashTypes.CRASH)
        OutlinedCard(
            modifier=modifier,
            border = CardDefaults.outlinedCardBorder().copy(brush = errorBrush),
            content = content)
    else
        OutlinedCard(
            modifier=modifier,
            content = content)
}